package com.saris.primego.service.impl;

import com.saris.primego.common.constant.StatusConstant;
import com.saris.primego.dao.DishRepository;
import com.saris.primego.dao.OrderRepository;
import com.saris.primego.dao.SetmealRepository;
import com.saris.primego.dao.UserRepository;
import com.saris.primego.pojo.entity.Orders;
import com.saris.primego.pojo.vo.BusinessDataVO;
import com.saris.primego.pojo.vo.DishOverViewVO;
import com.saris.primego.pojo.vo.OrderOverViewVO;
import com.saris.primego.pojo.vo.SetmealOverViewVO;
import com.saris.primego.service.WorkspaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    private final OrderRepository orderRepository;
    private final UserRepository userRepository;
    private final DishRepository dishRepository;
    private final SetmealRepository setmealRepository;

    public WorkspaceServiceImpl(OrderRepository orderRepository, UserRepository userRepository, DishRepository dishRepository, SetmealRepository setmealRepository) {
        this.orderRepository = orderRepository;
        this.userRepository = userRepository;
        this.dishRepository = dishRepository;
        this.setmealRepository = setmealRepository;
    }

    /**
     * 根据时间段统计营业数据
     * 营业额：当日已完成订单的总金额
     * 有效订单：当日已完成订单的数量
     * 订单完成率：有效订单数 / 总订单数
     * 平均客单价：营业额 / 有效订单数
     * 新增用户：当日新增用户的数量
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {

        //查询总订单数
        Long totalOrderCount = orderRepository.countByStatus(Orders.COMPLETED);

        //营业额
        double turnover = orderRepository.findAllByOrderTimeBetweenAndStatus(begin, end, Orders.COMPLETED)
                .stream()
                .map(Orders::getAmount)
                .filter(Objects::nonNull) // 防止空指针
                .mapToDouble(BigDecimal::doubleValue)
                .sum();

        //有效订单数
        Long validOrderCount = orderRepository.countByOrderTimeBetweenAndStatus(begin, end, Orders.COMPLETED);

        double unitPrice = 0.0;

        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 && validOrderCount != 0) {
            //订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
            //平均客单价
            unitPrice = Math.round(turnover / validOrderCount*100.0)/100.0;
        }

        //新增用户数
        long newUsers = userRepository.countByCreateTimeBetween(begin, end);

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount.intValue())
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers((int) newUsers)
                .build();
    }


    /**
     * 查询订单管理数据
     */
    public OrderOverViewVO getOrderOverView() {
        // 获取当天0时0分的时间点
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();

        //待接单
        long waitingOrders = orderRepository.countByOrderTimeAfterAndStatus(todayStart, Orders.TO_BE_CONFIRMED);

        //待派送
        long deliveredOrders = orderRepository.countByOrderTimeAfterAndStatus(todayStart, Orders.CONFIRMED);

        //已完成
        long completedOrders = orderRepository.countByOrderTimeAfterAndStatus(todayStart, Orders.COMPLETED);

        //已取消
        long cancelledOrders = orderRepository.countByOrderTimeAfterAndStatus(todayStart, Orders.CANCELLED);

        //全部订单
        long allOrders = orderRepository.count();

        return OrderOverViewVO.builder()
                .waitingOrders((int) waitingOrders)
                .deliveredOrders((int) deliveredOrders)
                .completedOrders((int) completedOrders)
                .cancelledOrders((int) cancelledOrders)
                .allOrders((int) allOrders)
                .build();
    }

    /**
     * 查询菜品总览
     */
    public DishOverViewVO getDishOverView() {
        long sold = dishRepository.countByStatus(StatusConstant.ENABLE);

        long discontinued = dishRepository.countByStatus(StatusConstant.DISABLE);

        return DishOverViewVO.builder()
                .sold((int) sold)
                .discontinued((int) discontinued)
                .build();
    }

    /**
     * 查询套餐总览
     */
    public SetmealOverViewVO getSetmealOverView() {
        long sold = setmealRepository.countByStatus(StatusConstant.ENABLE);

        long discontinued = setmealRepository.countByStatus(StatusConstant.DISABLE);

        return SetmealOverViewVO.builder()
                .sold((int) sold)
                .discontinued((int) discontinued)
                .build();
    }
}
